package org.wmq.shopmanager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.wmq.commonutil.result.Result;
import org.wmq.shopmanager.mapper.SystemMenuMapper;
import org.wmq.shopmanager.service.SystemMenuService;
import org.wmq.shopmodel.Entity.system.SystemMenu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class SystemMenuServiceImpl extends ServiceImpl<SystemMenuMapper, SystemMenu> implements SystemMenuService {
    private final SystemMenuMapper systemMenuMapper;

    @Override
    public List<SystemMenu> getNodes() {
        return this.getTreeStructureList();
        //return this.getSystemMenuListByParentId(0L);
    }

    @Override
    public Result<Void> removeById(Long id) {
        if (this.getChildrenCount(id) > 0){
            return Result.error("该菜单下存在子菜单，不能删除");
        }
        super.removeById(id);
        return Result.success();
    }

    @Override
    public List<SystemMenu> getNodesBySystemUserId(Long systemUserId) {
        List<SystemMenu> list = this.systemMenuMapper.getSytemMenuByUserId(systemUserId);
        return this.makeListToTreeStructure(list);
    }

    private List<SystemMenu> getSystemMenuListByParentId(Long parentId){
        LambdaQueryWrapper<SystemMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemMenu::getParentId,parentId);
        List<SystemMenu> result = this.systemMenuMapper.selectList(queryWrapper);
        if (result != null && !result.isEmpty()){
            for (SystemMenu systemMenu : result){
                systemMenu.setChildren(this.getSystemMenuListByParentId(systemMenu.getId()));
            }
        }
        return result;
    }

    private List<SystemMenu> getTreeStructureList(){
       return this.makeListToTreeStructure(this.list());
    }

    private List<SystemMenu> makeListToTreeStructure(List<SystemMenu> list){
        Map<Long, List<SystemMenu>> map = new HashMap<> ();
        for (SystemMenu systemMenu : list){
            Long parentId = systemMenu.getParentId();
            if (!map.containsKey(parentId)){
                map.put(parentId,new ArrayList<>());
            }
            map.get(parentId).add(systemMenu);
        }
        for (SystemMenu systemMenu : list){
            systemMenu.setChildren(map.get(systemMenu.getId()));
        }
        return map.get(0L);
    }
    private long getChildrenCount(Long id){
        LambdaQueryWrapper<SystemMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemMenu::getParentId,id);
        return this.systemMenuMapper.selectCount(queryWrapper);
    }
}
